<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //实现Object.defineproperty

        // let val = 'tom'
        // let person = {}
        // Object.defineProperty(person, 'name', {
        //     get() {
        //         console.log('name属性被读取了...');
        //         return val;
        //     },
        //     set(newVal) {
        //         console.log('name属性被修改了...');
        //         val = newVal;
        //     }
        // })

        // person.name = "Bobo"
        // console.log(person.name);

        // 以上已经可观测了,但是当对象属性太多时,需要一个一个定义,封装一下

        // 参考文档 https://blog.csdn.net/sinat_17775997/article/details/99690769

        function observable(obj) {
            if (!obj || typeof obj !== 'object') {
                return;
            }
            let keys = Object.keys(obj);
            keys.forEach((key) => {
                defineReactive(obj, key, obj[key])
            })
            return obj;
        }

        function defineReactive(obj, key, val) {
            let dep = new Dep()
            Object.defineProperty(obj, key, {
                enumerable: true,
                configurable: true,
                get() {
                    if (Dep.target) {
                        dep.addSub(Dep.target)
                    }
                    console.log(`${key}属性被读取了...`);
                    return val;
                },
                set(newVal) {
                    console.log(`${key}属性被修改了...`);
                    val = newVal;
                    dep.notify()
                }
            })
        }

        let peroson = observable({
            name: 'lhb',
            age: 18
        })

        console.log(peroson)
        console.log(peroson.name)
        console.log(peroson.age)
        peroson.age = 20
        console.log(peroson.age)


        // 创建订阅器,依赖收集容器,容纳所有的订阅者
        function Dep() {
            this.subs = []
        }
        Dep.prototype = {
            addSub: function(sub) {
                this.subs.push(sub)
            },
            notify: function() {
                this.subs.forEach(function(sub) {
                    sub.updata()
                })
            }
        }
        Dep.target = null
    </script>
</body>

</html>